<?php
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//
// DLMan by Shedd Technologies International		  				//
// http://www.dlman.com | info@dlman.com							//
// Copyright 2003 by STI, All rights reserved.						//
// ---------------------------------------------------------------- //
// Usage of this software is governed by the terms of GPL. 	    	//
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//

require_once("global.php");
error_reporting (E_ALL);
//CALL: dodownload.php?action=load&file_id=FILE&ln=txn_id

//check to see if the client has 
//	requested to be authenticated
if($faction=="load"){
	$Fauth=$file_id*31;//create a auth key value
	session_register("Fauth");
	//if authenticated, download file
	
	iff(verify($Muser,$Mpass),download($file_id,$ln));
}//end elseif auth=do
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
//	FUNCTIONS
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\

function download($file_id,$ln){
	global $config,$Muser,$stage;
	
	$sql="SELECT * FROM ".$config->dt['user']." WHERE ".$config->field['username']."='".$Muser."'";
	$result=mysql_query($sql);
	$value=mysql_fetch_array($result);
	$uid=$value[$config->field['userid']];
	$email=$value[$config->field['email']];
	
	$sql="SELECT * FROM ".$config->dt['transactions']." WHERE uid='".$uid."' AND txn_id='".$ln."' AND status='ACTIVE'";
	$result=mysql_query($sql);
	$trans=mysql_fetch_array($result);
	
	$sql="SELECT * FROM ".$config->dt['files']." WHERE id='".$file_id."'";
	$result=mysql_query($sql);
	$file=mysql_fetch_array($result);
	
	/////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////
	//is time left for download
	if(($file['permissions']=='free')&&($file['associated']=="NONE")){
		//file is freeware
		$timeleft=1;
	}//end freeware
	else{
		//file is paid or associated with paid
		if($file['associated']!="NONE"){
			//file is associated
			$sql="SELECT * FROM ".$config->dt['transactions']." WHERE uid='".$uid."' AND file_id='".$file['associated']."' AND status='ACTIVE'";
			$result=mysql_query($sql);
			$assoc=mysql_fetch_array($result);
			
			$sql="SELECT * FROM ".$config->dt['files']." WHERE id='".$file['associated']."'";
			$pfres=mysql_query($sql);
			$pfassoc=mysql_fetch_array($pfres);
			
			$begin_date=$assoc['update_timestamp'];
			//check that user has time left to download file
			$end_date=DateAdd($pfassoc['term_type'],$pfassoc['term'],$begin_date);
			$timeleft=DateDiff("s",time(),$end_date);
		}
		else{
			$begin_date=$trans['update_timestamp'];
			
			//check that user has time left to download file
			$end_date=DateAdd($file['term_type'],$file['term'],$begin_date);
			$timeleft=DateDiff("s",time(),$end_date);
		}
	}//end paid/associated
	
	//check timeleft
	if($timeleft<=0){
		die("Your download period has expired!");
	}
	/////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////
	//license file
	if(!isset($stage)){
		print dlicense($file_id,$file,$ln);//pass file's id and database data
	}//end first stage
	/////////////////////////////////////////////////////////////////////////
	//confirm user information
	elseif($stage=="1"){
		//check agreement
		global $HTTP_POST_VARS;
		$value="";
		print sheader();
		
		if(strlen($HTTP_POST_VARS['myinitials'])<=0) die("<b>You must agree to the license!</b>");
		//not free, associated
		if(($file['permissions']!='free')&&($file['associated']=="NONE")){
			//pull license data
			$sql="SELECT * FROM ".$config->dt['license']." WHERE id='".$file['license']."'";
			$result=mysql_query($sql);
			$value=mysql_fetch_array($result);
			//check additional data
			
			//check to make sure all fields were completed
			for($i=1;$i<6;$i++){
				$act="activated_$i";
				$ne="name_$i";
				if($value[$act]=="true"){
					if($HTTP_POST_VARS[$ne]=="") die("<b>You must complete all additional fields!</b>");
				}
			}//end for
		}//end not free, associated
		
		print confirm($HTTP_POST_VARS,$value,$ln);
		
		print $config->copypow.footer();
	}//end stage 1
	/////////////////////////////////////////////////////////////////////////
	//deliver file
	elseif($stage=="2"){
		global $Fauth,$HTTP_POST_VARS;
		
		if(isset($Fauth)&&isset($file_id)&&(($Fauth/31)==$file_id)){//validate request
			
			//LOG ENTRY INTO LOG TABLE
			$sql="INSERT INTO ".$config->dt['log']." (record_id,timestamp,user_id,file_id,txn_id) VALUES ('','".time()."','".$uid."','".$file_id."','".$ln."')";
			$result=mysql_query($sql);
			if(!$result){//FAILURE
				$error=mysql_error();
				//pull sales address from settings
				$sql="SELECT sales_address FROM ".$config->dt['settings']."";
				$result=mysql_query($sql);
				$value=mysql_fetch_array($result);
				$sa=$value['sales_address'];
				@mail($sa,"Logging Error!","An error occured when attempting to log the download of file $file_id (License: $ln) by user $uid.  The error was:\n\n$error\n\nFor technical support, please log into your administration area for instructions.", "From: Member Download System\r\n");
			}
			
			//not free, associated
			if(($file['permissions']!='free')&&($file['associated']=="NONE")){
				//LOG LICENSE DATA
				$sql="INSERT INTO ".$config->dt['license_data']." (id,uid,file_id,timestamp,data_1,data_2,data_3,data_4,data_5,txn_id) VALUES ('','".$uid."','".$file_id."','".time()."','".$HTTP_POST_VARS["name_1"]."','".$HTTP_POST_VARS["name_2"]."','".$HTTP_POST_VARS["name_3"]."','".$HTTP_POST_VARS["name_4"]."','".$HTTP_POST_VARS["name_5"]."','".$ln."')";
				$result=@mysql_query($sql);
				if(!$result){//FAILURE
					@mail($sa,"License Data Error!","An error occured when attempting to update a license data record during download. (License: $ln).  The error was:\n\n$error\n\nFor technical support, please log into your administration area for instructions.", "From: Member Download System\r\n");
				}
			}//end not freeware
			
			//INCREMENT DOWNLOAD COUNT
			$query = "SELECT downloads from ".$config->dt['files']." WHERE id='$file_id'";
			$result = @mysql_query($query);
			$dls = @mysql_result($result,0,"downloads");
			$dls++;
			$sql="UPDATE ".$config->dt['files']." SET downloads='$dls' WHERE id='$file_id'";
			$result=@mysql_query($sql);
			if(!$result){//FAILURE
				@mail($sa,"Download Count Error!","An error occured when attempting to update the download count of file $file_id (License: $ln).  The error was:\n\n$error\n\nFor technical support, please log into your administration area for instructions.", "From: Member Download System\r\n");
			}
			
			//RUN USER DEFINED EVAL CODE
			$sql="SELECT php from ".$config->dt['files']." where id=$file_id";
			$result=mysql_query($sql);
			$value=mysql_fetch_array($result);
			if($value['php']!="") eval($value['php']);
			
			//DELIVER FILE
			if(isset($file_id)){
				//get data from DB
			    $query = "SELECT data,properties from ".$config->dt['files']." where id='$file_id'";
			    $result = @mysql_query($query);
			    $data = @mysql_result($result,0,"data");
			    $type = @mysql_result($result,0,"properties");
				//break properites down into usable elements
				$property_array=explode("|",$type);
				$type=$property_array[2];
				$dfname=$property_array[0];
				$attachment = '';
				//send headers
				header("Content-disposition:$attachment filename=$dfname");
				header("Content-Length: ".strlen($data));
			    header("Content-type: $type");
			    echo $data;
			}//end file id set
		}//end validate request
		else{
			die("You must proceed through each step before downloading the file!");
		}
	}//end stage 2
	/////////////////////////////////////////////////////////////////////////
}//end function

//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\

/*
Display license and optional fields.
*/
function dlicense($file_id,$value,$ln){
	global $config,$PHP_SELF;
	
	//pull license data
	$sql="SELECT * FROM ".$config->dt['license']." WHERE id='".$value['license']."'";
	$result=mysql_query($sql);
	$license=mysql_fetch_array($result);
	
	//use license display template
	print sheader();
	print "<form action='".$PHP_SELF."' method='post'>";
	print license_parse(template("dodownload_license"),$license,$ln,$value);
	print "</form>";
	print $config->copypow.footer();
}

//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\

/*
Output user's entered optional license information and ask for confirmation.
*/
function confirm($HTTP_POST_VARS,$value,$ln){
	global $config,$HTTP_POST_VARS,$PHP_SELF,$faction,$file_id;
	
	print "<b>Please carefully review the selections and information that you have provided.</b><br><br>";
	print "<form action='".$PHP_SELF."' method='post' target='_blank'>";
	
	$sql="SELECT * FROM ".$config->dt['files']." WHERE id='".$file_id."'";
	$result=mysql_query($sql);
	$file=mysql_fetch_array($result);
	
	//not free, associated
	if(($file['permissions']!='free')&&($file['associated']=="NONE")){
		for($i=1;$i<6;$i++){
			$act="activated_$i";
			$hp="name_$i";
			if($value[$act]=="true"){
				print "<b>".$value[$hp].":</b>&nbsp;".$HTTP_POST_VARS[$hp]."<br>";
				print "<input type='hidden' name='$hp' value='".$HTTP_POST_VARS[$hp]."'>";
			}
			else{
				print "<input type='hidden' name='$hp' value=''>";
			}
		}//end for
	}//end not free/associated
	
	print "<b>File:</b>&nbsp;".$file['name']."<br>";
	
	print "<br><b>If this information is correct, please click <i>Confirm</i>.</b><br>";
	
	print "<input type='hidden' name='stage' value='2'>";
	print "<input type='hidden' name='".session_name()."' value='".session_id()."'>";
	print "<input type='hidden' name='faction' value='$faction'>";
	print "<input type='hidden' name='file_id' value='$file_id'>";
	print "<input type='hidden' name='ln' value='$ln'>";
	print '<div align="center"><input type="submit" value="Confirm"></div>';
	print "</form>";
	print '<div align="center"><a href="member.php?loc=mem_down"><b>Return to Member Area</b></a></div>';
}//end function confirm

//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\

/*
	Parse display license template.
		$license_name
		$text_of_license
		$optional_data
		$buttons
	*/
function license_parse($code,$value,$ln,$file){
	global $PHP_SELF,$config,$faction,$file_id;
	$data = @mysql_result($value,0,"data");
	$code=str_replace("{license_name}",$value['title'],$code);
	$code=str_replace("{text_of_license}","<!--LICENSE TEXT-->".$value['data']."<!--end LICENSE TEXT-->",$code);
	$opt_data="";
	
	//not free, associated
	if(($file['permissions']!='free')&&($file['associated']=="NONE")){
		//get existing data
		$sql='SELECT * FROM '.$config->dt['license_data'].' WHERE txn_id=\''.$ln.'\'';
		$result=mysql_query($sql);
		$data=@mysql_fetch_array($result);
		
		//gather optional data requests
		for($i=1;$i<6;$i++){
			$act="activated_$i";
			$hl="html_$i";
			$nm="data_$i";
			$ty="type_$i";
			
			if($value[$act]=="true"){
				//revert back from htmlspecialchars
				$value[$hl]=ereg_replace('&gt;', '>', $value[$hl]);
				$value[$hl]=ereg_replace('&lt;', '<', $value[$hl]);
				$value[$hl]=ereg_replace('&quot;', "\"", $value[$hl]);
				$value[$hl]=ereg_replace('&amp;', '&', $value[$hl]);
				
				//enter any existing data
				if($value[$ty]=="text"||$value[$ty]=="textbox") $html=str_replace('{v'.$i.'}',$data[$nm],$value[$hl]);
				elseif($value[$ty]=="select"){
					$html=str_replace('{'.$data[$nm].'-v'.$i.'}',"SELECTED",$value[$hl]);
				}
				elseif($value[$ty]=="radio"||$value[$ty]=="cb"){
					$html=str_replace('{'.$data[$nm].'-v'.$i.'}',"CHECKED",$value[$hl]);
				}
				//add the HTML to output
				$opt_data.=$html."<br>";
			}
		}
		if($opt_data!="")$opt_data="<b>Please enter the following information to download:</b><br>$opt_data<br>";
	}//end not free, associated
	//agreement?
	$opt_data.='Enter your initials to confirm your agreement to '.$value['title'].":&nbsp;<input type='text' name='myinitials' size='5'><input type='hidden' name='stage' value='1'><input type='hidden' name='ln' value='".$ln."'><input type='hidden' name='faction' value='$faction'><input type='hidden' name='file_id' value='$file_id'>";
	$code=str_replace("{optional_data}",$opt_data,$code);
	$code=str_replace("{buttons}",'<input type="submit" value="Download">&nbsp;&nbsp;<input type="Reset">',$code);
	return $code;
}

//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
?>
